package com.jstyle.jclifexd.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.android.flexbox.FlexboxLayoutManager;
import com.jstyle.jclifexd.NetWork.NetWorkUtil;
import com.jstyle.jclifexd.R;
import com.jstyle.jclifexd.activity.HeartTipsActivity;
import com.jstyle.jclifexd.adapter.HistoryShowAdapter;
import com.jstyle.jclifexd.adapter.SleepDetailAdapter;
import com.jstyle.jclifexd.daoManager.HeartDataDaoManager;
import com.jstyle.jclifexd.daoManager.SleepDataDaoManager;
import com.jstyle.jclifexd.daoManager.UserInfoDaoManager;
import com.jstyle.jclifexd.model.HeartData;
import com.jstyle.jclifexd.model.SleepData;
import com.jstyle.jclifexd.model.SleepDetail;
import com.jstyle.jclifexd.model.Sleepfordata;
import com.jstyle.jclifexd.model.UserInfo;
import com.jstyle.jclifexd.utils.ChartDataUtil;
import com.jstyle.jclifexd.utils.DateUtil;
import com.jstyle.jclifexd.utils.ResolveData;
import com.jstyle.jclifexd.utils.ScreenUtils;
import com.jstyle.jclifexd.utils.SharedPreferenceUtils;
import com.jstyle.jclifexd.utils.Utils;
import com.jstyle.jclifexd.view.ActivityHistoryCircleProgress;
import com.jstyle.jclifexd.view.SleepView;
import com.jstyle.jclifexd.view.sleepview.AllSleepView;
import com.jstyle.jclifexd.view.sleepview.DeepSleepView;
import com.jstyle.jclifexd.view.sleepview.LightSleepView;
import com.jstyle.jclifexd.view.sleepview.RemView;
import com.jstyle.jclifexd.view.sleepview.SoberView;
import com.jstyle.jclifexd.view.widget.MyNestedScrollView;

import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.view.LineChartView;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link SleepDayFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class SleepDayFragment extends BaseFragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.iv_activity_history_left)
    ImageView ivActivityHistoryLeft;

    @BindView(R.id.iv_activity_history_right)
    ImageView ivActivityHistoryRight;
    @BindView(R.id.RecyclerView_data_day)
    RecyclerView RecyclerViewDataDay;
    @BindView(R.id.LineChartView_sleep_status)
    LineChartView LineChartViewSleepStatus;
    @BindView(R.id.LineChartView_sleepHeartChart)
    LineChartView LineChartViewSleepHeartChart;
    @BindView(R.id.RecyclerView_sleepDetail)
    RecyclerView RecyclerViewSleepDetail;
    Unbinder unbinder;
    float showRight = 0;

    //睡眠数据标题
    @BindArray(R.array.sleep_detailContent_array)
    String[] detailTitle_array;
    //睡眠数据范围
    @BindArray(R.array.sleep_detailLimit_array)
    String[] detailLimit_array;
    @BindView(R.id.bt_nohr)
    Button btNohr;
    @BindView(R.id.bt_nosleep)
    Button btNosleep;
    @BindView(R.id.sleep_rl)
    RelativeLayout sleepRl;
    @BindView(R.id.NestedScrollView)
    MyNestedScrollView NestedScrollView;
    //睡眠数据内容
    private float[] contentArray = new float[6];
    @BindView(R.id.tv_data_day_deepSleepTime)
    TextView tvDataDayDeepSleepTime;
    @BindView(R.id.tv_data_day_lightSleepTime)
    TextView tvDataDayLightSleepTime;
    @BindView(R.id.tv_data_day_awakeTime)
    TextView tvDataDayAwakeTime;

    @BindView(R.id.bt_sleep_week_date)
    Button btSleepWeekDate;
    @BindView(R.id.sleep_circleView)
    ActivityHistoryCircleProgress sleepCircleView;
    @BindView(R.id.bt_avgSleepHR)
    Button btAvgSleepHR;
    @BindView(R.id.sleep_view)
    SleepView sleep_view;
    @BindView(R.id.sleep_start_endtime)
    TextView sleep_start_endtime;


    @BindView(R.id.sleep_styletext)
    TextView sleep_styletext;
    @BindView(R.id.sleep_hourvalue)
    TextView sleep_hourvalue;
    @BindView(R.id.fenzhongvalue)
    TextView fenzhongvalue;


    @BindView(R.id.allsleep_vaue)
    TextView allsleep_vaue;
    @BindView(R.id.DeepSleepView_vaue)
    TextView DeepSleepView_vaue;
    @BindView(R.id.LightSleepView_vaue)
    TextView LightSleepView_vaue;
    @BindView(R.id.RemView_vaue)
    TextView RemView_vaue;
    @BindView(R.id.SoberView_vaue)
    TextView SoberView_vaue;
    //百分比
    @BindView(R.id.baifenbi_one)
    TextView baifenbi_one;
    @BindView(R.id.baifenbi_two)
    TextView baifenbi_two;
    @BindView(R.id.baifenbi_there)
    TextView baifenbi_there;
    @BindView(R.id.baifenbi_four)
    TextView baifenbi_four;
    //等级
    @BindView(R.id.mubiao_two)
    TextView mubiao_two;
    @BindView(R.id.mubiao_there)
    TextView mubiao_there;
    @BindView(R.id.mubiao_four)
    TextView mubiao_four;
    @BindView(R.id.mubiao_five)
    TextView mubiao_five;
    @BindArray(R.array.string_bp_array)
    String[] arrayBp;
    @BindView(R.id.score_value)
    TextView score_value;
    @BindView(R.id.fraction_rt)
    RelativeLayout fraction_rt;
    @BindView(R.id.sleep_quality)
    TextView sleep_quality;

    @BindView(R.id.sleep_qualityvalue)
    TextView sleep_qualityvalue;


    @BindView(R.id.allsleep_view)
    AllSleepView allsleep_view;
    @BindView(R.id.DeepSleepView_view)
    DeepSleepView DeepSleepView_view;
    @BindView(R.id.LightSleepView_view)
    LightSleepView LightSleepView_view;
    @BindView(R.id.RemView_view)
    RemView RemView_view;
    @BindView(R.id.SoberView_view)
    SoberView SoberView_view;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    private static final String TAG = "SleepDayFragment";
    private String queryDate;

    private List<String> listContent = new ArrayList<>();
    private HistoryShowAdapter historyShowAdapter;

    private SleepDetailAdapter sleepDetailAdapter;
    private List<SleepDetail> sleepDetailArray = new ArrayList<>();
    private int avgHR = 0;
    private Typeface mFace;


    public SleepDayFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment SleepDayFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static SleepDayFragment newInstance(String param1, String param2) {
        SleepDayFragment fragment = new SleepDayFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_sleep_day, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        initData();
        return view;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
//        if (context instanceof OnFragmentInteractionListener) {
//            mListener = (OnFragmentInteractionListener) context;
//        } else {
//            throw new RuntimeException(context.toString()
//                    + " must implement OnFragmentInteractionListener");
//        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    private void addSleepDetail() {
        sleepDetailArray.clear();
        for (int i = 0; i < detailTitle_array.length; i++) {
            SleepDetail sleepDetail = new SleepDetail();
            sleepDetail.setTitle(detailTitle_array[i]);
            sleepDetail.setContent(contentArray[i]);
            sleepDetail.setLimit(detailLimit_array[i]);
            sleepDetailArray.add(sleepDetail);
        }
    }

    @OnClick({R.id.bt_sleepHeartTips, R.id.iv_activity_history_left, R.id.iv_activity_history_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_sleepHeartTips:
                startActivity(HeartTipsActivity.class, HeartTipsActivity.TipsType, HeartTipsActivity.TipsType_SleepHeart);
                break;
            case R.id.iv_activity_history_right:
                queryDate = DateUtil.getTomorrowDateString(queryDate);
                initData();
                break;
            case R.id.iv_activity_history_left:
                queryDate = DateUtil.getYesterdayDateString(queryDate);
                initData();
                break;
        }
    }

    static List<SleepData> sleepDataList;

    private void initData() {
        btSleepWeekDate.setText(DateUtil.getShowDaySleep(getActivity(), queryDate));
        String nowDate = DateUtil.getDefaultFormatTime(new Date());
        ivActivityHistoryRight.setEnabled(!queryDate.equals(nowDate));
        String lastDate = DateUtil.getTomorrowDateString(queryDate);
        List<SleepData> sleepDataList = SleepDataDaoManager.queryData(queryDate, lastDate);
        List<HeartData> heartDataList = HeartDataDaoManager.queryData(queryDate, lastDate);
        int[] fiveSleepDataone = new int[288];//288*5分钟
        for (int i = 0; i < fiveSleepDataone.length; i++) {
            fiveSleepDataone[i] = -1;//睡眠数据0为有效数据
        }

        for (SleepData sleepData : sleepDataList) {
            String time = sleepData.getTime();
            String data = sleepData.getDateString();
            int startCount = DateUtil.get5MIndex(time, queryDate + " 12:00:00");
            //   Log.i(TAG, "initData: " + time + " " + data + " " + startCount);
            if (startCount >= 288) break;
            fiveSleepDataone[startCount] = Integer.valueOf(data) == 0 ? (int) (1 + Math.random() * 7) : Integer.valueOf(data);
        }
        List<Integer> listSleep = new ArrayList<>();
        for (int i = 0; i < fiveSleepDataone.length; i++) {
            int value = fiveSleepDataone[i];
            if (value != -1) {
                for (int j = 0; j < 5; j++) {
                    listSleep.add(i * 5 + j);
                }
            }
        }
        int firstCount = 0;
        int offsetCount = 1;
        for (int i = 0; i < heartDataList.size(); i++) {
            String time = heartDataList.get(i).getTime();
            int startCount = DateUtil.get1MIndex(time, queryDate + " 12:00:00");
            if (listSleep.contains(startCount)) {
                if (firstCount == 0) {
                    firstCount = startCount;
                } else {
                    if (offsetCount == 1) {
                        offsetCount = startCount - firstCount;
                        Log.i(TAG, "initData: " + offsetCount);
                        break;
                    }
                }
            }
        }
        if (offsetCount == 0) offsetCount = 1;
        int[] heartDataArray = new int[1440 / offsetCount];//1分钟一个点。一天1440
//        int lastCount=listSleep.get(listSleep.size()-1);
//        int firstSleepCount=listSleep.get(0);
//
//
//        int length = fiveSleepData.length;
        float showLeft = -1;
        float showRight = 0;

        List<Integer> sleepTime = getSleepTime(fiveSleepDataone);
        if (sleepTime.size() != 0) {
            showLeft = sleepTime.get(0);
            showRight = sleepTime.get(sleepTime.size() - 1);
        }
        for (HeartData heartData : heartDataList) {
            String time = heartData.getTime();
            int data = heartData.getHeart();
            int startCount = DateUtil.getMIndex(time, queryDate + " 12:00:00", offsetCount);

            if (startCount >= 1440 / offsetCount) break;
            if (isInSleep(sleepTime, startCount * offsetCount)) {
                heartDataArray[startCount] = data;
            }

        }
        initHeartChartView(heartDataArray, showLeft, showRight, offsetCount);
        initSleepChartView(fiveSleepDataone, sleepTime);


        int[] fiveSleepData = new int[288 * 5];//288*5分钟
        for (int i = 0; i < fiveSleepData.length; i++) {
            fiveSleepData[i] = -1;//睡眠数据0为有效数据
        }
        int endCount = 0;
        String MYdata = "";
        int index = 0;





        for (SleepData sleepData : newdata(sleepDataList)) {
            index++;
            String time = sleepData.getTime();
            int startCount = DateUtil.get5MIndexer(time, queryDate + " 12:00:00");
            if (0 == endCount) {
                endCount = startCount;
                MYdata = sleepData.getDateString();
                for (int i = 0; i < 5; i++) {
                    fiveSleepData[startCount + i] = Integer.valueOf(sleepData.getDateString());
                }
            } else {

                if (startCount - endCount > 30) {
                    for (int i = 0; i < 5; i++) {
                        fiveSleepData[endCount + i] = Integer.valueOf(MYdata);
                    }
                    for (int i = 0; i < ((startCount - endCount) + 5); i++) {
                        fiveSleepData[(endCount + 5) + i] = -1;
                    }
                } else {
                    if (30 >= startCount - endCount&&startCount - endCount>5) {//如果数据小于30分钟的里面数据有间隔需要补全清醒的数据
                        for (int i = 0; i < 5; i++) {
                            fiveSleepData[(endCount + i)] = Integer.valueOf(MYdata);
                        }
                        int value = ((startCount) - (endCount + 5));
                        for (int i = 0; i < value + 1; i++) {
                            fiveSleepData[(endCount + 5) + i] = 500;
                        }
                    } else {
                        for (int i = 0; i < startCount - endCount; i++) {
                            fiveSleepData[endCount + i] = Integer.valueOf(MYdata);
                        }
                    }
                }
                endCount = startCount;
                MYdata = sleepData.getDateString();
                if (index == sleepDataList.size()) {
                    for (int i = 0; i < 5; i++) {
                        fiveSleepData[endCount + i] = Integer.valueOf(MYdata);
                    }
                }
            }
        }


        inintSleepData(fiveSleepData, true);

    }

    /**
     * 判断是否有那种-1并且睡眠小于30分钟的数据
     * @param sleepDataList
     * @return
     */
    private  List<SleepData> newdata( List<SleepData> sleepDataList){
        for (int i=0;i<sleepDataList.size();i++){
            if ((i + 1) != sleepDataList.size()) {
                SleepData a=sleepDataList.get(i);
                SleepData b=sleepDataList.get(i+1);
                long time=DateUtil.getGapMinutes(a.getTime(),b.getTime());
                if(time>5&&time<=30){
                    SleepData aa=new SleepData();
                    aa.setDateString("500");
                    aa.setTime(DateUtil.addfive((int)time, a.getTime(),"yy.MM.dd HH:mm:ss"));
                    sleepDataList.add(i + 1,aa);
                }
            }
        }
        return sleepDataList;

    }

    /**
     * 解析税点的数据
     *
     * @param fiveSleepData
     * isfive 是否是五分钟一个点的数据
     */
    int duration = 0;//睡眠总分钟
    int DeepSleepViewduration = 0;//深睡分钟
    int LightSleepViewduration = 0;//浅睡分钟
    int RemViewduration = 0;//快速眼动分钟
    int SoberViewduration = 0;//清醒分钟

    @SuppressLint("SetTextI18n")
    /**
     * isfive  这个区分是不是五分钟数据
     */
    private void inintSleepData(int[] fiveSleepData, boolean isfive) {
        for (int j = 0; j < fiveSleepData.length; j++) {
            if (fiveSleepData[j] != -1) {
                fiveSleepData[j] = ResolveData.getSleepLeveler(isfive ? fiveSleepData[j] / 5f : fiveSleepData[j]);
            }
        }


        //fiveSleepData=  ResolveData.newFiveSleepData(fiveSleepData);

        List<List<Sleepfordata>> ALLdata = new ArrayList<>();
        List<Sleepfordata> sleepfordata = null;
        boolean isbegin = false;
        int count = 0;
        for (int j = 0; j < fiveSleepData.length; j++) {
            if (j + 1 != fiveSleepData.length) {
                if (fiveSleepData[j] == -1 && fiveSleepData[j + 1] != -1) {
                    if (null != sleepfordata) {
                        if (sleepfordata.size() > 0) {
                            ALLdata.add(sleepfordata);
                        }
                        sleepfordata = new ArrayList<>();
                    } else {
                        sleepfordata = new ArrayList<>();
                    }
                    isbegin = false;
                    count = 0;
                }
                if (fiveSleepData[j] != -1 && null != sleepfordata) {
                    if (!isbegin) {
                        isbegin = true;
                        Sleepfordata sleepfordata1 = new Sleepfordata();
                        sleepfordata1.setIndex(fiveSleepData[j]);
                        sleepfordata1.setBegintime(DateUtil.getCountTimeer(j));
                        sleepfordata1.setCount(1);
                        sleepfordata.add(sleepfordata1);
                    } else {
                        if (null != sleepfordata && sleepfordata.size() != 0) {
                            if (fiveSleepData[j] == sleepfordata.get(count).getIndex()) {
                                sleepfordata.get(count).setEndtime(DateUtil.getCountTimeer(j));
                                sleepfordata.get(count).setCount(sleepfordata.get(count).getCount() + 1);
                            } else {
                                sleepfordata.get(count).setEndtime(DateUtil.getCountTimeer(j));
                                Sleepfordata sleepfordata1 = new Sleepfordata();
                                sleepfordata1.setIndex(fiveSleepData[j]);
                                sleepfordata1.setBegintime(DateUtil.getCountTimeer(j));
                                sleepfordata1.setCount(1);
                                sleepfordata.add(sleepfordata1);
                                count++;

                            }
                        }
                    }
                }
            }
        }
        if (null != sleepfordata && sleepfordata.size() != 0) {
            fraction_rt.setVisibility(View.VISIBLE);
            ALLdata.add(sleepfordata);
            for (int b = 0; b < ALLdata.size(); b++) {
                String Endtime = ALLdata.get(b).get(ALLdata.get(b).size() - 1).getBegintime();
                if (!TextUtils.isEmpty(Endtime)) {
                    int inedex = ALLdata.get(b).get(ALLdata.get(b).size() - 1).getCount();
                    ALLdata.get(b).get(ALLdata.get(b).size() - 1).setEndtime(DateUtil.addfive_or_one(1 * inedex, Endtime));
                }
            }
        }else{
            fraction_rt.setVisibility(View.GONE);
        }
        duration = 0;
        DeepSleepViewduration = 0;//深睡分钟
        LightSleepViewduration = 0;//浅睡分钟
        RemViewduration = 0;//快速眼动分钟
        SoberViewduration = 0;//清醒分钟
        if (ALLdata.size() != 0) {
            for (int i = 0; i < ALLdata.size(); i++) {
                for (int j = 0; j < ALLdata.get(i).size(); j++) {
                    switch (ALLdata.get(i).get(j).getIndex()) {
                        //3-0 //深睡 0, //浅睡 1 //清醒2 //rem 3
                        case 0://深睡
                            DeepSleepViewduration += ALLdata.get(i).get(j).getCount();
                            break;
                        case 1://浅睡
                            LightSleepViewduration += ALLdata.get(i).get(j).getCount();
                            break;
                        case 2://清醒
                            SoberViewduration += ALLdata.get(i).get(j).getCount();
                            break;
                        case 3://rem
                            RemViewduration += ALLdata.get(i).get(j).getCount();
                            break;
                    }
                    duration += ALLdata.get(i).get(j).getCount();
                }
            }
            sleep_styletext.setText(getString(R.string.Sleep_Time));
            sleep_hourvalue.setText(DateUtil.formatHour(duration));
            fenzhongvalue.setText(DateUtil.formatMinte(duration));
            int size = ALLdata.size() - 1;
            sleep_start_endtime.setText("(" + ALLdata.get(0).get(0).getBegintime() + "-" + ALLdata.get(size).get(ALLdata.get(size).size() - 1).getEndtime() + ")");
            sleep_view.setDataSource(ALLdata, new SleepView.Xylistener() {
                @Override
                public void ReadEcgData(Sleepfordata X) {
                    if (null != X) {
                        switch (X.getIndex()) {
                            case 0:
                                sleep_styletext.setText(getString(R.string.Deep_Sleep));
                                break;
                            case 1:
                                sleep_styletext.setText(getString(R.string.Light_Sleep));
                                break;
                            case 2:
                                sleep_styletext.setText(getString(R.string.Awake));
                                break;
                            case 3:
                                sleep_styletext.setText(getString(R.string.Rem));
                                break;
                        }
                        sleep_hourvalue.setText(DateUtil.formatHour(X.getCount()));
                        fenzhongvalue.setText(DateUtil.formatMinte(X.getCount()));
                        sleep_start_endtime.setText("(" + X.getBegintime() + "-" + X.getEndtime() + ")");
                    }
                }
            }, duration);

        } else {
            sleep_view.clearView();
            sleep_styletext.setText(getString(R.string.Sleep_Time));
            sleep_hourvalue.setText("0");
            fenzhongvalue.setText("0");
            sleep_start_endtime.setText("(00:00-00:00)");
        }

        //设置当前时间
        allsleep_vaue.setText(DateUtil.formatHour(duration) + getString(R.string.hour) +
                DateUtil.formatMinte(duration) + getString(R.string.min_labeler));
        DeepSleepView_vaue.setText(DateUtil.formatHour(DeepSleepViewduration) + getString(R.string.hour) +
                DateUtil.formatMinte(DeepSleepViewduration) + getString(R.string.min_labeler));
        LightSleepView_vaue.setText(DateUtil.formatHour(LightSleepViewduration) + getString(R.string.hour) +
                DateUtil.formatMinte(LightSleepViewduration) + getString(R.string.min_labeler));
        RemView_vaue.setText(DateUtil.formatHour(RemViewduration) + getString(R.string.hour) +
                DateUtil.formatMinte(RemViewduration) + getString(R.string.min_labeler));
        SoberView_vaue.setText(DateUtil.formatHour(SoberViewduration) + getString(R.string.hour) +
                DateUtil.formatMinte(SoberViewduration) + getString(R.string.min_labeler));

        DeepSleepView_view.setDataSource(DeepSleepViewduration);
        LightSleepView_view.setDataSource(LightSleepViewduration);
        RemView_view.setDataSource(RemViewduration);
        SoberView_view.setDataSource(SoberViewduration);

        List<Sleepfordata> data = new ArrayList<>();
        if (0 != DeepSleepViewduration) {
            data.add(new Sleepfordata(DeepSleepViewduration, Color.parseColor("#C25CFF")));
        }
        if (0 != LightSleepViewduration) {
            data.add(new Sleepfordata(LightSleepViewduration, Color.parseColor("#00CC60")));
        }
        if (0 != RemViewduration) {
            data.add(new Sleepfordata(RemViewduration, Color.parseColor("#76C4E8")));
        }
        if (0 != SoberViewduration) {
            data.add(new Sleepfordata(SoberViewduration, Color.parseColor("#FC7B3A")));
        }
        allsleep_view.setDataSource(duration, data);

        float sleepGoal = SharedPreferenceUtils.getFloat(SharedPreferenceUtils.KEY_Sleep_goal, 480f);
        Log.e("dasdad",sleepGoal+"");
        baifenbi_one.setText(Double.valueOf(duration / sleepGoal * 100d).intValue() >= 100 ? 100 + "%" : Double.valueOf(duration / sleepGoal * 100d).intValue() + "%");
        baifenbi_two.setText(Double.valueOf(DeepSleepViewduration / 72d * 100d).intValue() >= 100 ? 100 + "%" : Double.valueOf(DeepSleepViewduration / 72d * 100d).intValue() + "%");
        baifenbi_there.setText(Double.valueOf(LightSleepViewduration / 150d * 100d).intValue() >= 100 ? 100 + "%" : Double.valueOf(LightSleepViewduration / 150d * 100d).intValue() + "%");
        baifenbi_four.setText(Double.valueOf(RemViewduration / 192d * 100d).intValue() >= 100 ? 100 + "%" : Double.valueOf(RemViewduration / 192d * 100d).intValue() + "%");

        if (0 == duration) {
            mubiao_two.setText("---");
            mubiao_there.setText("---");
            mubiao_four.setText("---");
            mubiao_five.setText("---");
        } else {
            if (DeepSleepViewduration < 72) {
                mubiao_two.setText(arrayBp[1]);
            } else if (DeepSleepViewduration >= 72 && DeepSleepViewduration <= 150) {
                mubiao_two.setText(arrayBp[0]);
            } else {
                mubiao_two.setText(arrayBp[2]);
            }
            if (LightSleepViewduration < 150) {
                mubiao_there.setText(arrayBp[1]);
            } else if (LightSleepViewduration >= 150 && LightSleepViewduration <= 288) {
                mubiao_there.setText(arrayBp[0]);
            } else {
                mubiao_there.setText(arrayBp[2]);
            }
            if (RemViewduration < 192) {
                mubiao_four.setText(arrayBp[1]);
            } else if (RemViewduration >= 192 && RemViewduration <= 252) {
                mubiao_four.setText(arrayBp[0]);
            } else {
                mubiao_four.setText(arrayBp[2]);
            }
            //默认为正常
            mubiao_five.setText(arrayBp[2]);
            if (SoberViewduration < 20) {
                mubiao_five.setText(arrayBp[0]);
            } else {
                mubiao_five.setText(arrayBp[2]);
            }
        }


        //设置当前睡眠得分
        if (duration == 0) {
            score_value.setText("0");
        } else if (duration <= 330) {
            score_value.setText("60");
        } else if (duration >= 540) {
            score_value.setText("80");
        } else {
            if (duration == 435) {
                score_value.setText("100");
            } else if (duration < 435) {
                int value = Float.valueOf(60f + (duration - 330) / 105f * 40f).intValue();
                score_value.setText(value + "");
            } else {
                int value = Float.valueOf(80f + (540f - duration) / 105f * 20f).intValue();
                score_value.setText(value + "");
            }

        }
        UserInfo userInfo = UserInfoDaoManager.getUserByUid(NetWorkUtil.getUserId());
        if (userInfo == null) {
            userInfo = new UserInfo();
            userInfo.setUserId(NetWorkUtil.getUserId());
            UserInfoDaoManager.insertUser(userInfo);
        }

        if (duration <330) {
            sleep_quality.setText(getResources().getString(R.string.quality_Poor));
            if(userInfo.getGender()==0){
                sleep_qualityvalue.setText(getResources().getString(R.string.quality_Poor_man));
            }else{
                sleep_qualityvalue.setText(getResources().getString(R.string.quality_Poor_female));
            }

        } else if (duration >= 330&&duration <=540) {
            sleep_quality.setText(getResources().getString(R.string.quality_avg));
            if(userInfo.getGender()==0){
                sleep_qualityvalue.setText(getResources().getString(R.string.quality_avg_man));
            }else{
                sleep_qualityvalue.setText(getResources().getString(R.string.quality_avg_female));
            }
        } else {
            sleep_quality.setText(getResources().getString(R.string.quality_Good));
            if(userInfo.getGender()==0){
                sleep_qualityvalue.setText(getResources().getString(R.string.quality_Good_man));
            }else{
                sleep_qualityvalue.setText(getResources().getString(R.string.quality_Good_female));
            }
        }


    }

    private boolean isInSleep(List<Integer> sleepTime, int count) {
        boolean isInSleep = false;
        int sleepCount = sleepTime.size() / 2;
        for (int i = 0; i < sleepCount; i++) {
            int start = sleepTime.get(i * 2) * 5;
            int end = sleepTime.get(i * 2 + 1) * 5;

            if (count >= start && count <= end) {
                isInSleep = true;
                break;
            }
        }
        return isInSleep;
    }

    private List<Integer> getSleepTime(int[] fiveSleepData) {
        List<Integer> list = new ArrayList<>();
        int goBed = -1;
        int upBed = 0;
        int offCount = 0;
        for (int i = 0; i < fiveSleepData.length; i++) {
            int data = fiveSleepData[i];
            if (data != -1) {
                offCount = 0;
                if (goBed == -1) {
                    list.add(i);
                    goBed = i;
                }

            } else {
                offCount++;
                if (offCount > 6 && goBed != -1) {//30分钟离床
                    list.add(i - 6);
                    offCount = 0;
                    goBed = -1;
                }
            }
            if (i == fiveSleepData.length - 1 && goBed != -1) {
                list.add(i);
            }
        }
        return list;
    }

    public static List<SleepData> insertInIndex(int index, SleepData num) {
        int length = sleepDataList.size() + 1;
        List<SleepData> result = new ArrayList<>();
        for (int rIndex = 0; rIndex < length; rIndex++) {
            if (rIndex < index) {
                result.set(rIndex, sleepDataList.get(rIndex));
            } else if (rIndex == index) {
                result.set(rIndex, num);
            } else {
                result.set(rIndex, sleepDataList.get(rIndex - 1));
            }
        }
        return result;
    }

    private void initHeartChartView(int[] heartDataArray, float showLeft, float showRight, int offset) {
        int totalHR = 0;
        int count = 0;
        float maxDayHr = 0;
        float minDayHr = 300;

        for (int value : heartDataArray) {
            if (value != 0) {
                totalHR += value;
                count++;
                maxDayHr = Math.max(maxDayHr, value);
                minDayHr = Math.min(minDayHr, value);
            }
        }

        avgHR = totalHR == 0 ? 0 : totalHR / count;
        btNohr.setVisibility(totalHR == 0 ? View.VISIBLE : View.GONE);
        LineChartViewSleepHeartChart.setVisibility(totalHR == 0 ? View.GONE : View.VISIBLE);

        btAvgSleepHR.setText(String.format(getString(R.string.avg_sleep_heart), avgHR));
        float top = 0;
        if (maxDayHr % 10 == 0) {
            top = maxDayHr;
        } else {
            top = (((int) maxDayHr / 10) + 1) * 10;
        }
        ChartDataUtil.initDataSleepChartView(LineChartViewSleepHeartChart,
                -1, top + 10, 1440 / offset, minDayHr <= 40 ? minDayHr - 10 : 40, (showRight + 2) * (5f / offset), (showLeft - 2) * (5f / offset));

        LineChartViewSleepHeartChart.setLineChartData(ChartDataUtil.getSleepHeartDayChart(getActivity(), heartDataArray, mFace, offset, top));

    }


    private void init() {
        if (!Utils.IsRussian(getActivity())) {
            mFace = Typeface.createFromAsset(getActivity().getAssets(), "Brandon_reg.otf");
        } else {
            mFace = Typeface.createFromAsset(getActivity().getAssets(), "SourceHanSansCN-Regular.ttf");
        }

        sleepDetailAdapter = new SleepDetailAdapter(sleepDetailArray);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        RecyclerViewSleepDetail.setLayoutManager(linearLayoutManager);
        RecyclerViewSleepDetail.setAdapter(sleepDetailAdapter);

        String today = TextUtils.isEmpty(mParam1) ? DateUtil.getDefaultFormatTime(new Date()) : mParam1;
        queryDate = DateUtil.getYesterdayDateString(today);//第一次查询昨天睡觉数据

        FlexboxLayoutManager layoutManager2 = new FlexboxLayoutManager(getActivity());
        listContent.add(getString(R.string.avg_sleep_hr));
        listContent.add(getString(R.string.deep_sleep_time));
        listContent.add(getString(R.string.light_sleep_time));
        historyShowAdapter = new HistoryShowAdapter(listContent);
        RecyclerViewDataDay.setAdapter(historyShowAdapter);
        RecyclerViewDataDay.setLayoutManager(layoutManager2);
    }

    private void initSleepChartView(int[] stepData, List<Integer> sleepTime) {
        float sleepGoal = SharedPreferenceUtils.getFloat(SharedPreferenceUtils.KEY_Sleep_goal, 480);
        int[] sleepLevel = new int[3];
        for (float value : stepData) {
            if (value != -1) sleepLevel[ResolveData.getSleepLevel((int) value)]++;
        }
        float deep = sleepLevel[0];
        float light = sleepLevel[1];
        float awake = sleepLevel[2];
        Log.i(TAG, "initSleepChartView: " + deep + " " + light);
        float total = deep + light + awake;
        int duration = 0;
        if (sleepTime.size() >= 2) {
            int count = sleepTime.size() / 2;

            for (int i = 0; i < count; i++) {
                duration += sleepTime.get(i * 2 + 1) - sleepTime.get(i * 2);
            }

        }
        String totalTime = DateUtil.getPointSleepTime(getActivity(), (int) (duration * 5));
        String deepTime = DateUtil.getPointSleepTime(getActivity(), (int) (deep * 5));
        sleepCircleView.startAnimSleep(totalTime, total * 5 / sleepGoal);
        List<String> list = new ArrayList<>();
        list.add(String.valueOf(avgHR));
        list.add(deepTime);
        list.add(DateUtil.getPointSleepTime(getActivity(), (int) (light * 5)));
        historyShowAdapter.setStepData(list);
        float showLeft = 0;
        float showRight = 0;
        if (sleepTime.size() != 0) {
            showLeft = sleepTime.get(0);
            showRight = sleepTime.get(sleepTime.size() - 1);
        }
        // btNosleep.setVisibility(sleepTime.size() == 0 ? View.VISIBLE : View.GONE);
        //  LineChartViewSleepStatus.setVisibility(sleepTime.size() == 0 ? View.GONE : View.VISIBLE);
        // sleepRl.setVisibility(sleepTime.size() == 0 ? View.INVISIBLE : View.VISIBLE);
        ChartDataUtil.initDataSleepChartView(LineChartViewSleepStatus,
                -1, 80, stepData.length, 0, showRight + 10, showLeft - 10);

        LineChartViewSleepStatus.setLineChartData(ChartDataUtil.getSleepDayChart(getActivity(), stepData, sleepTime, mFace));
        float EfficiencyPercent = total == 0 ? 0 : (deep + light) / total;
        NumberFormat nf = NumberFormat.getPercentInstance();
        nf.setMinimumFractionDigits(1);
        double dsp = getSleepPercent(total, deep);
        double lsp = getSleepPercent(total, light);
        double asp = total == 0 ? 0 : getAwakePercent(dsp, lsp);
        Log.i(TAG, "initSleepChartView: " + asp);
        String deepSleepPercent = nf.format(dsp);
        String lightSleepPercent = nf.format(lsp);
        String awakeSleepPercent = nf.format(asp);
        try {
            double a = nf.parse(deepSleepPercent).doubleValue() +
                    nf.parse(lightSleepPercent).doubleValue();
            awakeSleepPercent = nf.format(total == 0 ? 0 : 1 - a);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        tvDataDayAwakeTime.setText(awakeSleepPercent);
        tvDataDayDeepSleepTime.setText(deepSleepPercent);
        tvDataDayLightSleepTime.setText(lightSleepPercent);
        contentArray[1] = total * 5;
        contentArray[2] = deep * 5;
        contentArray[3] = light * 5;
        contentArray[4] = EfficiencyPercent;
        contentArray[5] = avgHR;
        addSleepDetail();
        sleepDetailAdapter.setData(sleepDetailArray);
    }

    private double getAwakePercent(double dsp, double lsp) {
        Log.i(TAG, "getAwakePercent: ");
        int d = (int) Math.floor(dsp * 1000);
        int l = (int) Math.floor(lsp * 1000);
        return (1000 - d - l) / 1000f;
    }

    private double getSleepPercent(float total, float item) {
        return total == 0 ? 0 : item / total;
    }


    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    @Override
    public void shoot() {
        super.shoot();
        ScreenUtils.shareFile(getActivity(), NestedScrollView);
    }
}
